package com.wss.common.wechat.spi.app;

import com.wss.common.context.util.SystemConfig;
import com.wss.common.wechat.exception.WeixinException;
import com.wss.common.wechat.massage.InputMessage;
import com.wss.common.wechat.massage.MsgInfo;
import com.wss.common.wechat.massage.OutputMessage;
import com.wss.common.wechat.spi.IMessageHandler;
import com.wss.common.wechat.spi.app.event.IAppEventMessageHandler;
import com.wss.common.wechat.util.weixin.XStreamFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletInputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.IOException;
import java.io.StringReader;


/**
 * @author 赵飞
 * @version 用于处理微信消息
 */
@Component("appMessageHandler")
public class AppMessageHandler implements IMessageHandler {

	//应用级消息处理
	@Autowired
	private IAppEventMessageHandler appMessageHandler;

	@Override
	public String invoke(ServletInputStream inputStream) throws WeixinException {
		try {
			//将输入流转换为字符串
			String xmlMsg = XStreamFactory.inputStream2String(inputStream);
			if (true) {
				System.out.println("获取POST的消息:");
				System.out.println(xmlMsg);
				System.out.println("------------------------");
			}
			return this.invoke(xmlMsg);
		} catch (IOException ex) {
			throw new WeixinException("输入流转换错误：", ex);
		}
	}

	@Override
	public String invoke(String inputXml) throws WeixinException {
		//输出消息对象
		OutputMessage outputMsg = null;
		try {
			JAXBContext context = JAXBContext.newInstance(InputMessage.class);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			InputMessage inputMsg = (InputMessage) unmarshaller.unmarshal(new StringReader(inputXml));
			if (SystemConfig.isDebug()) {
				System.out.println("将指定节点下的xml节点数据转换为对象成功!");
			}

			String msgInfo = inputMsg.getInfoType();

			if (SystemConfig.isDebug()) {
				System.out.println("POST的消息类型:[msgInfo:" + msgInfo + "]");

			}

			//ticket消息处理
			if (msgInfo.equals(MsgInfo.Ticket.toString())) {
				//ticket
				appMessageHandler.ticketTypeMsg(inputMsg.toTicketInputMessage());
			} else if (msgInfo.equals(MsgInfo.Authorized.toString())) {
				//授权消息处理
				appMessageHandler.authTypeMsg(inputMsg.toAuthInputMessage());
			}


		} catch (SecurityException ex) {
			throw new WeixinException("安全错误：", ex);
		} catch (Exception ex) {
			throw new WeixinException("系统错误：", ex);
		}

		return "success";
	}


}
